package com.zgkj.Zip.tools;


import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.zgkj.Zip.form.AgentInfo;
import com.zgkj.Zip.form.Feeinfoall;
import com.zgkj.Zip.form.NoticeInfo;
import com.zgkj.Zip.form.NoticeSent;
import com.zgkj.Zip.form.PatentAgency;
import com.zgkj.Zip.service.IgnoreDTDEntityResolver;

public class XMLUtil {
	public static String getElementvalue(Element root, String name) {
		return root.elementTextTrim(name);
	}
	 public static Object fromXmlToBean(Element rootElt, Class pojo) throws Exception
      {
          // 首先得到pojo所定义的字段
          Field[] fields = pojo.getDeclaredFields();
          // 根据传入的Class动态生成pojo对象
          Object obj = pojo.newInstance();
          for (Field field : fields)
          {
              // 设置字段可访问（必须，否则报错）
              field.setAccessible(true);
              // 得到字段的属性名
              String name = field.getName();
              // 这一段的作用是如果字段在Element中不存在会抛出异常，如果出异常，则跳过。
              try
              {
                  rootElt.elementTextTrim(name);
                  //System.out.println(rootElt.elementTextTrim(name));
              }
              catch (Exception ex)
              {
                  continue;
              }
              if (rootElt.elementTextTrim(name) != null && !"".equals(rootElt.elementTextTrim(name)))
              {
                  // 根据字段的类型将值转化为相应的类型，并设置到生成的对象中。
                  if (field.getType().equals(Long.class) || field.getType().equals(long.class))
                  {
                      field.set(obj, Long.parseLong(rootElt.elementTextTrim(name)));
                  }
                  else if (field.getType().equals(String.class))
                  {
                      field.set(obj, rootElt.elementTextTrim(name));
                  }
                  else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
                  {
                      field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name)));
                  }
                  else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
                  {
                      field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name)));
                  }
                  else if (field.getType().equals(java.util.Date.class))
                  {
                      field.set(obj, Date.parse(rootElt.elementTextTrim(name)));
                  }
                  else
                  {
                      continue;
                  }
              }
              if (rootElt.attribute(name)!= null && !"".equals(rootElt.attribute(name)))
              {
                  // 根据字段的类型将值转化为相应的类型，并设置到生成的对象中。
                  if (field.getType().equals(Long.class) || field.getType().equals(long.class))
                  {
                      field.set(obj, Long.parseLong(rootElt.attributeValue(name)));
                  }
                  else if (field.getType().equals(String.class))
                  {
                      field.set(obj, rootElt.attributeValue(name));
                  }
                  else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
                  {
                      field.set(obj, Double.parseDouble(rootElt.attributeValue(name)));
                  }
                  else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
                  {
                      field.set(obj, Integer.parseInt(rootElt.attributeValue(name)));
                  }
                  else if (field.getType().equals(java.util.Date.class))
                  {
                      field.set(obj, Date.parse(rootElt.attributeValue(name)));
                  }
                  else
                  {
                      continue;
                  }
              }
          }
          return obj;
  }


	 public static List fromXmlToBeanList(List arrayList, Class pojo) throws Exception
	 {
		List  list = new ArrayList();
		for (int i = 0; i < arrayList.size(); i++) {
			list.add(fromXmlToBean((Element)arrayList.get(i),pojo));
		}
		return list;

	 }
	 public static void listNodes(Element node){
	       // System.out.println("当前节点的名称：" + node.getName());
	        //首先获取当前节点的所有属性节点
	        List<Attribute> list = node.attributes();
	        //遍历属性节点
	        for(Attribute attribute : list){
	            System.out.println("属性"+attribute.getName() +":" + attribute.getValue());
	        }
	        //如果当前节点内容不为空，则输出
	        if(!(node.getTextTrim().equals(""))){
	             System.out.println( node.getName() + "：" + node.getText());
	        }
	        //同时迭代当前节点下面的所有子节点
	        //使用递归
	        Iterator<Element> iterator = node.elementIterator();
	        while(iterator.hasNext()){
	            Element e = iterator.next();
	            listNodes(e);
	        }
	    }
	 public static NoticeInfo getNoticeInfo(String filepath) throws Exception {
		    NoticeInfo NoticeInfo = new NoticeInfo();
	        SAXReader reader = new SAXReader();
	        reader.setEntityResolver(new IgnoreDTDEntityResolver()); // ignore dtd
	       // reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
	        Document doc = reader.read(new File(filepath));
	        Element root = doc.getRootElement();
	        NoticeInfo = (NoticeInfo) XMLUtil.fromXmlToBean(root, NoticeInfo.class);
	        List a = doc.selectNodes("//cn_notice_info/fee_info_all/fee_info/fee");
//	        if(a==null||a.size()==0){
//	        	a = doc.selectNodes("//cn_notice_info/fee_info/fee");
//	        }
	        List<Feeinfoall> FeeinfoallList = XMLUtil.fromXmlToBeanList(a, Feeinfoall.class);
	        PatentAgency PatentAgency = (PatentAgency) XMLUtil.fromXmlToBean((Element)doc.selectObject("//cn_notice_info/patent_agency"), PatentAgency.class);
	        List<AgentInfo> AgentInfoList = XMLUtil.fromXmlToBeanList(doc.selectNodes("//cn_notice_info/patent_agency/agent_info"), AgentInfo.class);
	        NoticeSent noticesent = (NoticeSent) XMLUtil.fromXmlToBean((Element)doc.selectObject("//cn_notice_info/notice_sent"), NoticeSent.class);
	        if(doc.selectNodes("//cn_notice_info/fee_info_all").size()==1){
	        	String annual_year = XMLUtil.getElementvalue((Element)doc.selectObject("//cn_notice_info/fee_info_all"), "annual_year");
	        	NoticeInfo.setAnnual_year(annual_year);
	        	String cost_slow_flag = XMLUtil.getElementvalue((Element)doc.selectObject("//cn_notice_info/fee_info_all"), "cost_slow_flag");
	        	NoticeInfo.setCost_slow_flag(cost_slow_flag);
	        }
	        PatentAgency.setAgent_info(AgentInfoList);
	        NoticeInfo.setNotice_sent(noticesent);
	        NoticeInfo.setFee_info_all(FeeinfoallList);
	        NoticeInfo.setPatent_agency(PatentAgency);


	        List applicant_info_List = doc.selectNodes("//cn_notice_info/applicant_info/applicant_name");
	        String applicant_info = "";
	        for (Object element : applicant_info_List) {
	        	Node node = (Node) element;
	        	//System.out.println(node.getStringValue());
	        	if(applicant_info!=""){
	        		applicant_info =applicant_info+ "/";
	        	}
	        	applicant_info = applicant_info +node.getStringValue();
			}
	        NoticeInfo.setApplicant_info(applicant_info);
	        return NoticeInfo;
	}



	 public static void main(String[] args) throws Exception {
		String aString = "C:\\Users\\KCF\\Desktop\\kcf\\123.xml";

		//System.out.println(aString);
		NoticeInfo NoticeInfo  = XMLUtil.getNoticeInfo(aString);
		//System.out.println(NoticeInfo.getCost_slow_flag());
		//System.out.println(NoticeInfo.getAnnual_year());
//		if(aBoolean){
//			System.out.println();
//		}
	}
}
